const Question = require("../db/model/questions")
const User = require("../db/model/users")
const { SuccessModel, ErrorModel } = require("../utils/resModel")

class QuestionCtl {
    /**
     * 获取话题列表
     * @param {*} ctx 
     */
    async find(ctx) {
        const { per_page = 10 } = ctx.query
        const perPage = Math.max(parseInt(per_page), 1)
        const page = Math.max(parseInt(ctx.query.page), 1) - 1
        const q = new RegExp(ctx.query.q)
        const list = await Question.find({ $or: [{ title: q }, { description: q }] }).limit(perPage).skip(page * perPage)
        ctx.body = new SuccessModel(list)
    }

    /**
     * 根据id查询一个话题
     * @param {*} ctx 
     */
    async findById(ctx) {
        const { fields = "" } = ctx.query
        let selectFields = fields.split(";").filter(f => f).map(f => ' +' + f).join(" ")
        const question = await Question.findById(ctx.params.id).select(selectFields).populate("questioner topics")
        ctx.body = new SuccessModel(question)
    }

    /**
     * 检查该问题是否属于该用户
     * @param {*} ctx 
     * @param {*} next 
     */
    async checkQuestioner(ctx, next) {
        const { question } = ctx.state
        if (question.questioner.toString() !== ctx.state.user._id) {
            ctx.throw(403, "没有权限操作")
        }
        await next()
    }

    /**
     * 查询问题是否存在
     * @param {*} ctx 
     * @param {*} next 
     */
    async checkQuestionExist(ctx, next) {
        const question = await Question.findById(ctx.params.id).select("+questioner")
        if (!question) {
            ctx.throw(404, "问题不存在")
        }
        ctx.state.question = question
        await next()
    }

    /**
     * 创建一个问题
     * @param {*} ctx 
     */
    async create(ctx) {
        ctx.verifyParams({
            title: { type: "string", required: true },
            description: { type: "string", required: false },
            topics: { type: "array", required: false }
        })
        const question = await new Question({ ...ctx.request.body, questioner: ctx.state.user._id }).save()
        ctx.body = new SuccessModel(question)
    }

    /**
     * 修改一个问题
     * @param {*} ctx 
     */
    async update(ctx) {
        ctx.verifyParams({
            title: { type: "string", required: false },
            description: { type: "string", required: false },
            topics: { type: "array", required: false }
        })
        const question = await ctx.state.question.update(ctx.request.body)
        ctx.body = new SuccessModel(question)
    }

    /**
     * 删除一个问题
     * @param {*} ctx 
     */
    async deleteQuestion(ctx) {
        const question = await Question.findByIdAndRemove(ctx.params.id)
        ctx.body = new SuccessModel(question)
    }

}



module.exports = new QuestionCtl()